<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件传输系统</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            line-height: 1.6;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
            color: #333;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        h1 {
            text-align: center;
            color: #2c3e50;
            margin-bottom: 30px;
        }
        .drop-area {
            border: 2px dashed #3498db;
            border-radius: 8px;
            padding: 40px;
            text-align: center;
            background-color: #fff;
            transition: all 0.3s ease;
            margin-bottom: 20px;
        }
        .drop-area.active {
            border-color: #2ecc71;
            background-color: #f8fff8;
        }
        .drop-area h2 {
            margin: 0 0 10px 0;
            color: #34495e;
        }
        .drop-area p {
            margin: 0 0 20px 0;
            color: #7f8c8d;
        }
        .btn {
            display: inline-block;
            background-color: #3498db;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s ease;
        }
        .btn:hover {
            background-color: #2980b9;
        }
        #fileInput {
            display: none;
        }
        .message {
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 20px;
            font-weight: bold;
        }
        .message.success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .message.error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .file-info {
            background-color: #e8f4f8;
            padding: 15px;
            border-radius: 4px;
            border: 1px solid #b3e5fc;
        }
        .progress-container {
            margin-top: 30px;
        }
        .progress-bar {
            width: 100%;
            height: 20px;
            background-color: #e0e0e0;
            border-radius: 10px;
            overflow: hidden;
            margin-bottom: 10px;
        }
        .progress-fill {
            height: 100%;
            background-color: #3498db;
            width: 0%;
            transition: width 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 12px;
        }
        .transfer-stats {
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .transfer-stats h3 {
            margin-top: 0;
            color: #2c3e50;
        }
        .stat-item {
            display: flex;
            justify-content: space-between;
            padding: 5px 0;
            border-bottom: 1px solid #eee;
        }
        .stat-item:last-child {
            border-bottom: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>文件传输系统</h1>
        
        <!-- 消息显示区域 -->
        <div th:if="${message}" class="message" th:classappend="${status} == 'success' ? 'success' : 'error'">
            <span th:text="${message}"></span>
        </div>
        
        <!-- 文件信息显示 -->
        <div th:if="${fileName}" class="file-info">
            <p>正在传输文件: <strong th:text="${fileName}"></strong></p>
        </div>
        
        <!-- 拖拽上传区域 -->
        <form id="uploadForm" action="/upload" method="post" enctype="multipart/form-data">
            <div id="dropArea" class="drop-area">
                <h2>将文件拖拽到这里</h2>
                <p>或者</p>
                <label for="fileInput" class="btn">选择文件</label>
                <input type="file" id="fileInput" name="file" required />
            </div>
            
            <button type="submit" class="btn" style="width: 100%;">开始传输</button>
        </form>
        
        <!-- 传输统计信息区域 -->
        <div class="transfer-stats">
            <h3>传输信息</h3>
            <div class="stat-item">
                <span>状态:</span>
                <span id="transferStatus">等待上传</span>
            </div>
            <div class="stat-item">
                <span>进度:</span>
                <span id="transferProgress">0%</span>
            </div>
            <div class="stat-item">
                <span>速度:</span>
                <span id="transferSpeed">--</span>
            </div>
        </div>
    </div>
    
    <script>
        // 获取DOM元素
        const dropArea = document.getElementById('dropArea');
        const fileInput = document.getElementById('fileInput');
        const uploadForm = document.getElementById('uploadForm');
        const transferStatus = document.getElementById('transferStatus');
        const transferProgress = document.getElementById('transferProgress');
        const transferSpeed = document.getElementById('transferSpeed');
        
        // 拖拽相关事件
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            dropArea.addEventListener(eventName, preventDefaults, false);
        });
        
        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }
        
        ['dragenter', 'dragover'].forEach(eventName => {
            dropArea.addEventListener(eventName, highlight, false);
        });
        
        ['dragleave', 'drop'].forEach(eventName => {
            dropArea.addEventListener(eventName, unhighlight, false);
        });
        
        function highlight() {
            dropArea.classList.add('active');
        }
        
        function unhighlight() {
            dropArea.classList.remove('active');
        }
        
        // 处理文件拖拽
        dropArea.addEventListener('drop', handleDrop, false);
        
        function handleDrop(e) {
            const dt = e.dataTransfer;
            const files = dt.files;
            
            if (files.length > 0) {
                fileInput.files = files;
                updateDropAreaText(files[0].name);
            }
        }
        
        // 处理文件选择
        fileInput.addEventListener('change', function() {
            if (this.files.length > 0) {
                updateDropAreaText(this.files[0].name);
            }
        });
        
        function updateDropAreaText(fileName) {
            dropArea.innerHTML = `
                <h2>已选择文件</h2>
                <p>${fileName}</p>
                <label for="fileInput" class="btn">更换文件</label>
                <input type="file" id="fileInput" name="file" style="display: none;" />
            `;
            
            // 重新绑定事件
            const newFileInput = document.getElementById('fileInput');
            newFileInput.addEventListener('change', function() {
                if (this.files.length > 0) {
                    updateDropAreaText(this.files[0].name);
                }
            });
        }
        
        // 使用AJAX进行异步上传
        uploadForm.addEventListener('submit', function(e) {
            e.preventDefault(); // 阻止默认表单提交
            
            if (!fileInput.files.length) {
                alert('请先选择一个文件');
                return;
            }
            
            transferStatus.textContent = '正在上传...';
            transferProgress.textContent = '0%';
            
            const formData = new FormData(this);
            const xhr = new XMLHttpRequest();
            
            // 监听上传进度
            xhr.upload.addEventListener('progress', function(e) {
                if (e.lengthComputable) {
                    const percentComplete = Math.round((e.loaded / e.total) * 100);
                    transferProgress.textContent = percentComplete + '%';
                    
                    // 添加进度条填充效果
                    const progressFill = document.querySelector('.progress-fill');
                    if (progressFill) {
                        progressFill.style.width = percentComplete + '%';
                        progressFill.textContent = percentComplete + '%';
                    }
                }
            });
            
            // 监听上传完成
            xhr.addEventListener('load', function() {
                if (xhr.status === 200) {
                    transferStatus.textContent = '上传成功';
                    
                    // 解析响应（假设返回JSON格式）
                    try {
                        const response = JSON.parse(xhr.responseText);
                        if (response.message) {
                            // 显示成功消息
                            const messageDiv = document.createElement('div');
                            messageDiv.className = 'message success';
                            messageDiv.textContent = response.message;
                            const container = document.querySelector('.container');
                            container.insertBefore(messageDiv, container.firstChild);
                        }
                    } catch (e) {
                        console.error('解析响应失败:', e);
                    }
                } else {
                    transferStatus.textContent = '上传失败';
                    
                    const messageDiv = document.createElement('div');
                    messageDiv.className = 'message error';
                    messageDiv.textContent = '上传失败，请重试';
                    const container = document.querySelector('.container');
                    container.insertBefore(messageDiv, container.firstChild);
                }
            });
            
            // 监听上传错误
            xhr.addEventListener('error', function() {
                transferStatus.textContent = '上传出错';
                
                const messageDiv = document.createElement('div');
                messageDiv.className = 'message error';
                messageDiv.textContent = '网络错误，请检查连接';
                const container = document.querySelector('.container');
                container.insertBefore(messageDiv, container.firstChild);
            });
            
            // 发送请求
            xhr.open('POST', '/upload');
            xhr.send(formData);
        });
        
        // 模拟传输速度显示
        function updateTransferSpeed() {
            // 实际应用中，这里可以通过计算已上传数据量和时间来计算真实速度
            // 这里简单模拟一些速度值
            const speeds = ['2.5 MB/s', '3.1 MB/s', '2.8 MB/s', '3.5 MB/s', '4.0 MB/s'];
            let currentSpeedIndex = 0;
            
            setInterval(() => {
                if (transferStatus.textContent === '正在上传...' || 
                    transferStatus.textContent === '准备传输...' || 
                    transferStatus.textContent === '正在传输...') {
                    currentSpeedIndex = (currentSpeedIndex + 1) % speeds.length;
                    transferSpeed.textContent = speeds[currentSpeedIndex];
                } else if (transferStatus.textContent === '等待上传') {
                    transferSpeed.textContent = '--';
                } else if (transferStatus.textContent === '上传成功') {
                    transferSpeed.textContent = '完成';
                }
            }, 2000);
        }
        
        // 启动速度更新
        updateTransferSpeed();
        
        // 添加进度条填充元素到进度条容器
        window.addEventListener('DOMContentLoaded', function() {
            const progressBar = document.querySelector('.progress-bar');
            if (progressBar && !progressBar.querySelector('.progress-fill')) {
                const progressFill = document.createElement('div');
                progressFill.className = 'progress-fill';
                progressFill.textContent = '0%';
                progressBar.appendChild(progressFill);
            }
        });
    </script>
</body>
</html>